// api/http.ts
import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'

// 定义业务错误码
export const ERROR_CODES = {
  NETWORK_ERROR: 'NETWORK_ERROR',
  UNAUTHORIZED: 'UNAUTHORIZED',
  PERMISSION_DENIED: 'PERMISSION_DENIED',
  VALIDATION_ERROR: 'VALIDATION_ERROR',
  SERVER_ERROR: 'SERVER_ERROR',
  NOT_FOUND: 'NOT_FOUND'
}

// 扩展错误类型
export interface ApiError extends Error {
  code?: string
  response?: any
}

// 创建axios实例
const http = axios.create({
  baseURL: 'http://localhost:9001/api/v1',
  timeout: 60000, // 增加到60秒，给大数据导入更多时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
http.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      if (!config.headers) {
        config.headers = {}
      }
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    // 特殊类型直接返回
    if (response.config.responseType === 'blob' || response.data instanceof Blob) {
      return response;
    }
    
    // 业务状态码检查
    if (response.data && response.data.code !== 0) {
      const error = new Error(response.data.message || '请求失败') as ApiError;
      error.response = response;
      // 根据后端返回的code设置错误码
      switch (response.data.code) {
        case 401:
          error.code = ERROR_CODES.UNAUTHORIZED;
          break;
        case 403:
          error.code = ERROR_CODES.PERMISSION_DENIED;
          break;
        case 404:
          error.code = ERROR_CODES.NOT_FOUND;
          break;
        case 500:
          error.code = ERROR_CODES.SERVER_ERROR;
          break;
        default:
          error.code = ERROR_CODES.NETWORK_ERROR;
      }
      return Promise.reject(error);
    }
    
    // 只返回data部分
    return response.data;
  },
  (error) => {
    console.error('API请求错误:', error)
    const apiError = new Error(error.message || '网络错误') as ApiError;
    apiError.code = ERROR_CODES.NETWORK_ERROR;
    return Promise.reject(apiError)
  }
)

export default http